<template>
	<div class="app-container">
		<el-form class="base-search-form" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
			<el-form-item label="所属公司" prop="companyId">
				<el-tree-select
					v-model="queryParams.companyId"
					:data="companyList"
					:render-after-expand="true"
					:props="treeProps"
					node-key="id"
					check-strictly
					@change="companyChange" />
			</el-form-item>
			<el-form-item label="所属部门" prop="department">
				<el-select v-model="queryParams.departId" placeholder="请选择" clearable @change="departmentChange">
					<el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>

			<!-- <el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item> -->
		</el-form>

    <div class="base-container mt-10px">
      <div class="top-card">
        <div class="top-card-box">
          <p class="num" id="totalUser">{{ total.num.toFixed(0) }}</p>
          <div class="flex items-center">
            <p class="dot-1"></p>
            <p class="label">资产总数</p>
          </div>
        </div>
        <div class="top-card-box">
          <p class="num" id="totalUser">{{ total.num1.toFixed(0) }}</p>
          <div class="flex items-center">
            <p class="dot-2"></p>
            <p class="label">使用中</p>
          </div>
        </div>
        <div class="top-card-box">
          <p class="num" id="totalUser">{{ total.num2.toFixed(0) }}</p>
          <div class="flex items-center">
            <p class="dot-3"></p>
            <p class="label">待维修</p>
          </div>
        </div>
        <div class="top-card-box">
          <p class="num" id="totalUser">{{ total.num3.toFixed(0) }}</p>
          <div class="flex items-center">
            <p class="dot-4"></p>
            <p class="label">维修中</p>
          </div>
        </div>
        <div class="top-card-box last-card">
          <p class="num" id="totalUser">{{ total.num4.toFixed(0) }}</p>
          <div class="flex items-center">
            <p class="dot-5"></p>
            <p class="label">已报废</p>
          </div>
        </div>
      </div>
    </div>

		<div class="mt-10px">
			<el-row :gutter="10" justify="space-between">
				<el-col :span="12">
					<div class="base-container">
						<div class="title">资产状态分布</div>

						<div id="assetStatus" class="echarts"></div>
					</div>
				</el-col>
				<el-col :span="12">
					<div class="base-container">
						<div class="title">资产类型分布</div>

						<div id="assetType" class="echarts"></div>
					</div>
				</el-col>
			</el-row>

			<div style="height: 10px"></div>

			<el-row :gutter="10" justify="space-between">
				<el-col :span="12">
					<div class="base-container">
						<div class="title">资产数量统计</div>

						<div id="assetNum" class="echarts"></div>
					</div>
				</el-col>
				<el-col :span="12">
					<div class="base-container">
						<div class="title">资产状态统计</div>

						<div id="assetStatusNum" class="echarts"></div>
					</div>
				</el-col>
			</el-row>
		</div>
	</div>
</template>

<script setup name="Report">
import { getReportApi } from '@/api/asset/report'
import { getAllCompanies } from '@/api/company/company'
import { listDepartment } from '@/api/company/department'
import { circle_pie, chart_bar } from '@/utils/echarts'
import { deepClone } from '@/utils/index'
import * as echarts from 'echarts'
import { useTransition, TransitionPresets } from '@vueuse/core'
import Big from 'big.js'

const { proxy } = getCurrentInstance()
const { fixed_assets_type, fixed_assets_status } = proxy.useDict('fixed_assets_type', 'fixed_assets_status')

const loading = ref(true)
const showSearch = ref(true)
const departmentList = ref([])
const companyList = ref([])
const treeProps = {
	label: 'name',
	disabled: (data, node) => {
		return data.check == false
	}
}
const duration = 1000
const total = ref({
  num: 0,           // 总数
  num1: 0,          // 使用中
  num2: 0,          // 待维修
  num3: 0,          // 维修中
  num4: 0,          // 已报废
})

const data = reactive({
	queryParams: {
		companyId: null,
		departId: null
	}
})

const { queryParams } = toRefs(data)

function companyChange() {
	queryParams.value.departId = null
	getDepartmentList()
	handleQuery()
}

function departmentChange() {
	handleQuery()
}

/** 公司列表 */
function getCompanyList() {
	getAllCompanies().then((res) => {
		companyList.value = res.data || []
    if (companyList.value.length) {
      const company = companyList.value[0]
      if (company.check) {
        queryParams.value.companyId = company.id
      } else if (company.children.length) {
        queryParams.value.companyId = company.children[0].id
      }
      getDepartmentList()
      handleQuery()
    }
	})
}

/** 部门列表 */
function getDepartmentList() {
	const params = {
		pageNum: 1,
		pageSize: 100,
		companyId: queryParams.value.companyId
	}
	listDepartment(params).then((response) => {
		if (queryParams.value.companyId) {
			departmentList.value = response.rows
		} else {
			departmentList.value = []
		}
	})
}

function getList() {
	loading.value = true
	getReportApi(queryParams.value).then((response) => {
		const { assetStatus, assetType, departAssetNum, departAssetStatus } = response.data
    // 总数
    setTotalAnimation(assetStatus)

		// 资产状态饼图
		setAssetStatusPie(assetStatus)

    // 资产类型饼图
    setAssetTypePie(assetType)

    // 资产数量柱状图
    setAssetNumBar(departAssetNum)

    // 资产状态柱状图
    setAssetStatusNumBar(departAssetStatus)
    
		loading.value = false
	})
}

// 资产状态饼图
function setAssetStatusPie(data) {
	const list = data.map((item) => {
		const obj = fixed_assets_status.value.find((i) => i.value == item.asset_status)
		return {
			name: obj ? obj.label : item.asset_status,
			value: item.num
		}
	})
	const dom = document.getElementById('assetStatus')
	if (echarts.getInstanceByDom(dom)) {
		echarts.dispose(dom)
	}
	const chart = echarts.init(dom)
	let options = deepClone(circle_pie)
	// options.color = ['#7F94FD', '#F09591', '#F7CF52', '#D7E0E3']
	options.series[0].data = list
  options.toolbox.feature.saveAsImage.name = '资产状态分布'
	chart.setOption(options, true)
}

// 资产类型饼图
function setAssetTypePie(data) {
	const list = data.map((item) => {
		const obj = fixed_assets_type.value.find((i) => i.value == item.asset_type)
		return {
			name: obj ? obj.label : item.asset_type,
			value: item.num
		}
	})
	const dom = document.getElementById('assetType')
	if (echarts.getInstanceByDom(dom)) {
		echarts.dispose(dom)
	}
	const chart = echarts.init(dom)
	let options = deepClone(circle_pie)
	// options.color = ['#7F94FD', '#F09591', '#F7CF52', '#D7E0E3']
	options.series[0].data = list
  options.toolbox.feature.saveAsImage.name = '资产类型分布'
	chart.setOption(options, true)
}

// 资产数量柱状图
function setAssetNumBar(data) {
  let xData = []
  let yData = []
  data.forEach(obj => {
    xData.push(obj.name)
    yData.push(obj.num)
  })
  const dom = document.getElementById('assetNum')
	if (echarts.getInstanceByDom(dom)) {
		echarts.dispose(dom)
	}
	const chart = echarts.init(dom)
	let options = deepClone(chart_bar)
  options.xAxis.data = xData
  options.legend.data = []
  options.series = [
    {
      type: 'bar',
      data: yData
    }
  ]
  options.toolbox.feature.saveAsImage.name = '资产数量统计'
	chart.setOption(options, true)
}

// 资产状态柱状图
function setAssetStatusNumBar(data) {
  let xData = []
  let series = []
  let legend = fixed_assets_status.value.map(item => {
    return item.label
  })
  let keyArr = Object.keys(data)
  keyArr.forEach(key => {
    let list = data[key]
    if (list.length) {
      xData.push(list[0].name)
    } else {
      xData.push('')
    }
  })
  fixed_assets_status.value.forEach(status => {
    let yData = []
    keyArr.forEach(key => {
      let list = data[key]
      yData.push(getAssetNum(status.value, list))
    })
    series.push({
      name: status.label,
      type: 'bar',
      data: yData
    })
  })
  const dom = document.getElementById('assetStatusNum')
	if (echarts.getInstanceByDom(dom)) {
		echarts.dispose(dom)
	}
	const chart = echarts.init(dom)
	let options = deepClone(chart_bar)
  options.xAxis.data = xData
  options.legend.data = legend
  options.series = series
  options.toolbox.feature.saveAsImage.name = '资产状态统计'
	chart.setOption(options, true)
}

/** 搜索按钮操作 */
function handleQuery() {
	getList()
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm('queryRef')
	handleQuery()
}

// 统计数字滚动动画
const setTotalAnimation = (data) => {
  // 字典存储的状态：1使用中  2维修中   3待维修   4已报废
  let totalRes = {
    num: 0,
    num1: getAssetNum(1, data),
    num2: getAssetNum(3, data),
    num3: getAssetNum(2, data),
    num4: getAssetNum(4, data),
  }
  totalRes.num = new Big(totalRes.num1).plus(new Big(totalRes.num2)).plus(new Big(totalRes.num3)).plus(new Big(totalRes.num4)).toNumber()

  const num = ref(total.value.num)
  total.value.num = useTransition(num, {
    duration: duration
  })
  num.value = totalRes.num

  const num1 = ref(total.value.num1)
  total.value.num1 = useTransition(num1, {
    duration: duration
  })
  num1.value = totalRes.num1

  const num2 = ref(total.value.num2)
  total.value.num2 = useTransition(num2, {
    duration: duration
  })
  num2.value = totalRes.num2

  const num3 = ref(total.value.num3)
  total.value.num3 = useTransition(num3, {
    duration: duration
  })
  num3.value = totalRes.num3

  const num4 = ref(total.value.num4)
  total.value.num4 = useTransition(num4, {
    duration: duration
  })
  num4.value = totalRes.num4
}

const getAssetNum = (status, data) => {
  const obj = data.find(item => {
    return item.asset_status == status
  })
  return obj ? Number(obj.num) : 0
}

getCompanyList()
</script>

<style scoped lang="scss">
@import url('@/assets/styles/statistic.scss');

.title {
	font-weight: bold;
}

.echarts {
	width: 100%;
	height: 300px;
}

.top-card-box {
  width: 20%;

  .dot, .dot-1, .dot-2, .dot-3, .dot-4, .dot-5 {
    width: 6px;
    height: 6px;
    border-radius: 3px;
    margin-right: 5px;
  }

  .dot-1 {
    background-color: blue;
  }

  .dot-2 {
    background-color: green;
  }

  .dot-3 {
    background-color: orange;
  }

  .dot-4 {
    background-color: red;
  }

  .dot-5 {
    background-color: gray;
  }
}

</style>
